class Bookmark < ActiveRecord::Base
  belongs_to :book
  validates_presence_of :page_number
  acts_as_nested_set

  def bounds=(bnds)
    self.x, self.y, self.width, self.height = bnds
    page_image = book.pages[page_number].image
    bnds[0] = Integer(self.x * page_image.columns)
    bnds[1] = Integer(self.y * page_image.rows)
    bnds[2] = Integer(self.width * page_image.columns)
    bnds[3] = Integer(self.height * page_image.rows)
    self.image = page_image.crop(bnds[0], bnds[1], bnds[2], bnds[3])
  end

  def page
    book.pages[page_number]
  end

  def image_file_name
    File.join(PDF_BOOKS_DIR,"%03d.%03d.%03d.jpg" % [book_id, page_number, id])
  end

  def image=(img)
    @not_saved = true
    @image = img
  end
  
  def image
    @image ||= Magick::Image.read(image_file_name).first
  end
  
  def after_save
    save_image if @not_saved
  end
  
  protected
  def save_image
    @image.write(image_file_name)
  end
  
end
